//
//  ViewController.m
//  Class-22-第三方上拉下拉刷新
//
//  Created by Apple on 17/6/12.
//  Copyright (c) 石虎. All rights reserved.
//

#import "ViewController.h"
#import "MJRefresh/MJRefresh.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,MJRefreshBaseViewDelegate>{
    
    UITableView *table;
    NSMutableArray *arr;
    MJRefreshFooterView *foot; //尾部
    MJRefreshHeaderView *header;//头部
}
//@property (nonatomic,strong)UITableView *tableView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //创建 table
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    table.dataSource = self;
    table.delegate = self;
    [self.view addSubview: table];
    
    //添加数据到数组
    arr = [NSMutableArray arrayWithObjects:@"123",@"345",@"123",@"345",@"123",@"345", nil];
    
    
    
    
    //尾部实例化
    foot = [MJRefreshFooterView footer];
    foot.scrollView = table;
    foot.delegate = self;
    
    //头部实例化
    header = [MJRefreshHeaderView header];
    header.scrollView = table;
    header.delegate = self;
    
    //开始刷新
    [header beginRefreshing];
    
}
#pragma mark -  实现自动刷新代理
//开始刷新
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView{
    if ([refreshView isKindOfClass:[MJRefreshHeaderView class]])
        
    {
        //延迟2秒以后调用
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            //添加数据
            [arr addObject:@"new123"];
            
            [table reloadData];
            //停止刷新
            [header endRefreshing];
        });
    }
    else{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            //删除数组第一个
            [arr removeObjectAtIndex:0];
            [table reloadData];
            //停止刷新
            [foot endRefreshing];
        });
    }

}





//共多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arr.count;
}
//每行显示的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString *cellId = @"cellid";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    //缓存池
    if (!cell) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    //赋值每一行 cell 的数据
    cell.textLabel.text = arr[indexPath.row];
    return cell;
}
//尾部 组的个数
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

@end
